package com.zretc.notice.service;

import com.zretc.api.pojo.Notice;
import com.zretc.notice.dao.NoticeMapper;
import com.zretc.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private RedisService redisService;
    public List<Notice> queryNoticesByAmount(Integer index,Integer pageNum)
    {
        String redisKey="noticeList:"+index+","+pageNum;
        List<Notice> result=redisService.getCacheList(redisKey);
        if (CollectionUtils.isEmpty(result))
        {
            result=noticeMapper.getNoticesByAmount(index, pageNum);
            if (CollectionUtils.isEmpty(result))return null;
            redisService.setCacheList(redisKey,result);
        }
        redisService.expire(redisKey,5);
        return result;
    }
    public Notice queryNoticeById(Integer id)
    {
        String redisKey="notice:"+id;
        Notice result=redisService.getCacheObject(redisKey);
        if (Objects.isNull(result))
        {
            result=noticeMapper.getNoticeById(id);
            if (Objects.isNull(result))return null;
            redisService.setCacheObject(redisKey,result);

        }
        redisService.expire(redisKey,5);
        return result;
    }
    public boolean publishNotice(Notice notice)
    {
        return noticeMapper.addSingleRecord(notice)==1;
    }
    public boolean topNotice(Integer id,boolean isTopped)
    {
        return isTopped ? noticeMapper.updateIsToppedToTrueById(id) == 1
                : noticeMapper.updateIsToppedToFalseById(id) == 1;
    }
    public boolean deleteNotice(Integer id, Date updateAt, Integer updateBy)
    {
        return noticeMapper.deleteSingleRecord(id, updateAt, updateBy)==1;
    }
    public boolean updateNotice(Notice notice)
    {
        return noticeMapper.updateNotice(notice)==1;
    }
}
